package com.gongsir.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.util.Map;

/**
 * @author 码之泪殇
 * @date 2020/8/27 13:53
 * 到达胜利之前，无法回头
 * 七牛文件上传工具, 上传文件,返回文件路径
 */
@Slf4j
public class QiNiuUtil {

    /**
     * 外链域名地址
     */
    public static String URL_PREFIX = "http://cdn.gongsir.club/";

    /**
     * AccessKey
     */
    public static String ACCESS_KEY = "ue2FujLsqY29jnno6lTqOiukrcUJ9H8ocxc9tlup";

    /**
     * SecretKey
     */
    public static String SECRET_KEY = "VTgUSh3as4k8rDPTiJSCJoRYDRggD5ZI1U75B5yu";

    /**
     * 存储空间名称
     */
    public static String BUCKET_NAME = "gongsir";


    /**
     * 上传文件
     */
    public static String upload2QiNiu(FileInputStream file, String uploadFileName) {
        //构造一个带指定Zone对象的配置类
        //zone2() 代表华南
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = uploadFileName;
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET_NAME);
        try {
            Response response = uploadManager.put(file, key, upToken, null, null);
            //解析上传成功的结果
            String bodyString = response.bodyString();
            ObjectMapper objectMapper = new ObjectMapper();
            Map map = objectMapper.readValue(bodyString, Map.class);
            String hash = (String) map.get("key");
            if (!StringUtils.isNullOrEmpty(hash)) {
                return URL_PREFIX + uploadFileName;
            }
            log.info(response.bodyString());
            // 访问路径
            log.info(URL_PREFIX + uploadFileName);
        } catch (QiniuException ex) {
            Response r = ex.response;
            log.error(r.toString());
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}


